package org.computumus.core.servlet;

import org.computumus.core.service.CodeService.Code;
import org.computumus.core.service.CodeService.CodeNotFoundException;
import org.computumus.core.service.CodeService.CodeServiceFactory;
import org.computumus.core.session.Session;
import org.computumus.core.session.SessionUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Set;

/**
 * Created by IntelliJ IDEA.
 * User: planadecu
 * Date: 25 juin 2010
 * Time: 18:58:40
 * To change this template use File | Settings | File Templates.
 */

public class CodeProvider extends javax.servlet.http.HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Session session = SessionUtils.getSession(request);

        Set<String> params = request.getParameterMap().keySet();
        PrintWriter out = response.getWriter();
        if(params.size()>1){
            out.println("Error, too many arguments");
            out.close();
            return;
        }
        Code code;
        try{
            if(params.size()==0){
                code = CodeServiceFactory.getCodeService().getCode(session);
            }else{
                try{
                    Long codeId = Long.parseLong(params.iterator().next());
                    code = CodeServiceFactory.getCodeService().getCodeById(codeId);
                }catch(NumberFormatException ex){
                    out.println("Not valid argument.");
                    return;
                }
            }
            out.println(code.getCode());
        }catch(CodeNotFoundException ex){
            out.println(ex.getMessage());
        }finally{
            out.close();
        }

    }
}
